package com.shengdong.water.feature.management.inspection

import android.annotation.SuppressLint
import android.graphics.Typeface
import android.text.TextUtils
import android.util.Log
import android.view.Gravity
import android.widget.LinearLayout
import android.widget.TextView
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.lifecycleScope
import androidx.lifecycle.repeatOnLifecycle
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager
import com.alibaba.android.arouter.facade.annotation.Route
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import com.shengdong.water.R
import com.shengdong.water.base.BaseVMActivity
import com.shengdong.water.code.adapter.DataRowAdapter
import com.shengdong.water.code.adapter.VideoAdapter
import com.shengdong.water.code.config.RouterConfig
import com.shengdong.water.code.config.UserConfig
import com.shengdong.water.code.router.RouterManager
import com.shengdong.water.code.utils.GridSpaceItemDecoration
import com.shengdong.water.code.utils.SpannableUtil
import com.shengdong.water.code.viewmodel.MonitorDetailViewModel
import com.shengdong.water.databinding.ActivityMonitorDetailBinding
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.launch

@Route(path = RouterConfig.Management.MONITOR_DETAIL_PATH)
@AndroidEntryPoint
class MonitorDetailActivity : BaseVMActivity <ActivityMonitorDetailBinding, MonitorDetailViewModel>()  {


    override fun getLayoutId() = R.layout.activity_monitor_detail
    val videoAdapter = VideoAdapter()

    private var address = ""
    private var signLangLat = ""
    private lateinit var dataRowAdapter: DataRowAdapter
    private var isHeaderScrollingByUser = false
    private val headerOrder = listOf(
        "COD/COD-Mn浓度", "氨氮浓度", "总磷浓度", "总氮浓度",
        "PH", "水温", "溶解氧", "浊度", "电导率",
        "总量", "瞬时量", "液位"
    )

    override fun initViews() {
        super.initViews()
        setTitle("监测详情")
        binding.viewModel = viewModel
        binding.labelUsername.setContent(UserConfig.user?.userName?:"")
        binding.recyclerVideos.layoutManager = GridLayoutManager(this@MonitorDetailActivity,3)
        binding.recyclerVideos.setHasFixedSize(true)
        binding.recyclerVideos.addItemDecoration(GridSpaceItemDecoration(spacing = 10))
        binding.recyclerVideos.adapter = videoAdapter

        tablesHeader()
        binding.recyclerRows.layoutManager = LinearLayoutManager(this@MonitorDetailActivity)
        dataRowAdapter = DataRowAdapter(this, emptyMap(), headerOrder, onRowScrolled = { _, scrollX ->
            if(!isHeaderScrollingByUser){
                binding.headerScroll.scrollTo(scrollX,0)
            }
        })

        binding.recyclerRows.adapter = dataRowAdapter
        setupScrollListeners()
        binding.labelMap.setOnClickListener {
            RouterManager.build(RouterConfig.Management.MONITOR_MAP_PATH)
                .withString("name",binding.labelPosition.getContent())
                .withString("address", address)
                .withString("code",binding.labelCode.getContent())
                .withString("langlat", binding.labelCoordinate.getContent())
                .withString("signLangLat", signLangLat)
                .navigate()
        }
    }
    private fun tablesHeader() {
        binding.tableHeader.removeAllViews()
        headerOrder.forEach { headerText ->
            // addTextViewToLayout(binding.layoutTableHeaderContent, headerText, isHeader = true)
            // (使用你之前定义的 addTextViewToLayout 辅助方法)
            val textView = TextView(this).apply {
                this.text = headerText
                layoutParams = LinearLayout.LayoutParams(
                    resources.getDimensionPixelSize(R.dimen.dp150),
                    LinearLayout.LayoutParams.WRAP_CONTENT
                ).also {
                    if (binding.tableHeader.childCount > 0) {
                        it.marginStart = resources.getDimensionPixelSize(R.dimen.dp1)
                    }
                }
                setPadding(
                    resources.getDimensionPixelSize(R.dimen.dp10),
                    resources.getDimensionPixelSize(R.dimen.dp10),
                    resources.getDimensionPixelSize(R.dimen.dp10),
                    resources.getDimensionPixelSize(R.dimen.dp10)
                )
                gravity = Gravity.CENTER
                setTypeface(null, Typeface.BOLD)
            }
            binding.tableHeader.addView(textView)
        }
    }

    @SuppressLint("ClickableViewAccessibility")
    private fun setupScrollListeners() {
        binding.headerScroll.setOnTouchListener { _, _-> true}
        binding.recyclerRows.setOnScrollChangeListener { _, scrollX, _, _, _ ->
            if(isHeaderScrollingByUser){
                dataRowAdapter.setHorizontalScrollForVisibleRow(scrollX)
            }
        }

//        binding.headerScroll.setOnTouchListener { _, event ->
//            when (event.action) {
//                android.view.MotionEvent.ACTION_DOWN -> {
//                    isHeaderScrollingByUser = true
//                }
//                android.view.MotionEvent.ACTION_UP, android.view.MotionEvent.ACTION_CANCEL -> {
//                    isHeaderScrollingByUser = false
//                }
//            }
//            false // 返回 false 以允许滚动事件继续被 HorizontalScrollView 处理
//        }
    }
    override fun initData() {
        super.initData()
        val id: String? = intent.getStringExtra("id")
        id?.let { viewModel.getDetail(it) }
    }


    override fun getViewModelClass() = MonitorDetailViewModel::class.java

    override fun showLoading(loading: String) {
        super.showLoading(loading)

    }

    override fun observeData() {
        super.observeData()
        lifecycleScope.launch {
            repeatOnLifecycle(Lifecycle.State.STARTED){
                viewModel.detail.collect { detail ->
                    detail?.let {
                        address = detail.detailAddress
                        signLangLat = detail.signLon + "," + detail.signLat
                        binding.labelTime.setContent(detail.createTime)
                        binding.labelCondition.setContent(detail.isSampleName)
                        binding.labelCode.setContent(detail.code)
                        binding.labelPosition.setContent(detail.name)
                        binding.labelDescribe.setContent(detail.profile)
                        binding.labelCoordinate.setContent("${detail.lon},${detail.lat}")
                        if(TextUtils.isEmpty(detail.remark)){
                            binding.labelRemark.setContent("-")
                        }else {
                            binding.labelRemark.setContent(detail.remark)
                        }

                        binding.labelMap.setContent("点击查看地图")
                        videoAdapter.setItems(detail.videoUrl.split(",").filter { !TextUtils.isEmpty(it) })
                        try {
                            val gson = Gson()
                            val dataMap: Map<String, String> = gson.fromJson(detail.waterQuality, object : TypeToken<Map<String, String>>() {}.type)
                            dataRowAdapter.updateSingleRowData(dataMap)

                            val scrollX = binding.headerScroll.scrollX
                            dataRowAdapter.setHorizontalScrollForVisibleRow(scrollX)
                        }catch (e:Exception){
                            dataRowAdapter.updateSingleRowData(emptyMap())
                        }

                    }
                }
            }

        }
    }

}